package com.spice.im;


import java.io.Serializable;

import java.text.DecimalFormat;
import java.util.ArrayList;





















import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.maxwin.view.XListViewHeader;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;
























//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.beem.push.utils.Constants;
import com.beem.push.utils.NotificationDetailsActivity;
import com.dodola.model.DuitangInfo;
import com.dodola.model.DuitangInfoAdapter;
import com.dodola.model.GreetInfo;
import com.dodola.model.GreetInfoAdapter;
import com.dodola.model.UnReadMsgNumber;
import com.dodowaterfall.widget.FlowView;
import com.example.android.bitmapfun.util.ObjectCache;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.nostra13.universalimageloader.core.ImageLoader;
//import com.stb.core.pojo.UploadFileRequest;
//import com.speed.im.login.ContactGroup;
import com.speed.im.login.ContactGroupListIQ;
import com.speed.im.login.ContactGroupListIQResponse;
import com.speed.im.login.ContactGroupListIQResponseProvider;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.ContactListsFragment.OnPtrlvListener;
import com.spice.im.GreetInfosFragment.OnPtrlvListener2;
import com.spice.im.SimpleListDialog.onSimpleListItemClickListener;
//import com.spice.im.attendance.AttendanceActivity;
import com.spice.im.attendance.AttendanceActivity2;
import com.spice.im.chat.ChatActivity;
import com.spice.im.chat.ChatPullRefListActivity;
import com.spice.im.gps.GpsSearchResPullRefListActivity;
import com.spice.im.group.GroupDetailsActivity;
import com.spice.im.group.GroupNew2Activity;
import com.spice.im.group.GroupNewActivity;
import com.spice.im.group.GroupPickContactsActivity;
import com.spice.im.group.MucCreateActivity;
import com.spice.im.preference.PreferenceActivity;
import com.spice.im.ui.BadgeView;
import com.spice.im.ui.CustomListView;
import com.spice.im.ui.HandyTextView;
import com.spice.im.ui.CustomListView.OnLoadMoreListener;
import com.spice.im.ui.CustomListView.OnRefreshListener;
import com.spice.im.utils.ConstantValues;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.ImageFetcher;
import com.spice.im.utils.TextUtils;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.SwitcherButton.onSwitcherButtonClickListener;
import com.stb.core.chat.BeemChatManager;
import com.stb.core.chat.ContactGroup;
import com.stb.core.uuid.DeviceUuidFactory2;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
//import com.stb.isharemessage.R;
//import com.stb.isharemessage.service.Contact;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IChat;
import com.stb.isharemessage.service.aidl.IChatManager;
import com.stb.isharemessage.service.aidl.IChatManagerListener;
import com.stb.isharemessage.service.aidl.IMessageListener;
import com.stb.isharemessage.service.aidl.IRoster;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.service.aidl.IBeemRosterListener;
import com.stb.isharemessage.ui.feed.OtherFeedListActivity;
//import com.stb.isharemessage.ui.ContactFrameActivity.StaggeredPullRefAdapter.ViewHolderGreetInfo;
import com.stb.isharemessage.utils.BeemConnectivity;
//import com.test.HandyTextView;
//import com.test.MainActivity;
//import com.test.R;

//import dalvik.system.VMRuntime;
























import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ext.SatelliteMenu;
import android.view.ext.SatelliteMenuItem;
import android.view.ext.SatelliteMenu.SateliteClickedListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.RecyclerListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.spice.im.utils.SwitcherButton.SwitcherButtonState;
import com.spiceim.db.TContactGroupAdapter;

import android.widget.ListView;
public class ContactFrameActivity extends BaseActivity implements IConnectionStatusCallback,OnPtrlvListener,OnPtrlvListener2,OnClickListener{
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
	private Context mContext;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
	
    private final static float TARGET_HEAP_UTILIZATION = 0.75f;
    private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
    private static final Intent SERVICE_INTENT = new Intent();
	static {
		//pkg,cls
//		SERVICE_INTENT.setComponent(new ComponentName("com.test", "com.stb.isharemessage.BeemService"));
//		SERVICE_INTENT.setComponent(new ComponentName("com.stb.isharemessage", "com.stb.isharemessage.BeemService"));
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
//		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.ServiceAssist"));
	}
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
    	LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}
	private final ServiceConnection mServConn = new BeemServiceConnection();
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    protected FlippingLoadingDialog mLoadingDialog;
    private HeaderLayout mHeaderLayout;
    private XListViewHeader xListViewHeader;
    private ImageFetcher mImageFetcher;
	private int itemWidth;
	private int column_count = 3;// 显示列数 just for image cut
//	protected void showLoadingDialog(String text) {
//		if (text != null) {
//			mLoadingDialog.setText(text);
//		}
//		mLoadingDialog.show();
//	}
//
//	protected void dismissLoadingDialog() {
//		if (mLoadingDialog.isShowing()) {
//			mLoadingDialog.dismiss();
//		}
//	}
    
	protected void showLoadingDialog() {
		findViewById(R.id.pb).setVisibility(View.VISIBLE);	
	}

	protected void dismissLoadingDialog() {
		findViewById(R.id.pb).setVisibility(View.GONE);
	}
	
//	private Button btn;
	private final OkListener mOkListener = new OkListener();
//	private TextView udidTextView;
    //----------------------版块滑动部分数据---------------------------//
    private int screenWidth;//屏幕的宽度
	private int imgWidth;   // 图片宽度
	private int currentView=0;// 当前视图
	private int viewOffset;// 动画图片偏移量
	
	//----------------------刷新部分数据----------------------------//
	private static final int LOAD_DATA_FINISH = 10;
	private static final int REFRESH_DATA_FINISH = 11;
	private static final int REFRESH_ROSTER_FINISH = 12;
	private static final int DELETE_ROSTER_FINISH = 13;
	private static final int UPDATE_ROSTER_FINISH = 14;
	private static final int ZHIDING_ROSTER_FINISH = 15;
	
	private CustomListAdapter mAdapter;
//	private CustomListView mListView;
	private PullToRefreshListView ptrlv = null;
	
	private final ContactGroupListOnClick mOnContactClick = new ContactGroupListOnClick();/**单击某联系人，打开chat聊天对话框*/
	
//	private LinkedList<ContactGroup> tempList;
	private Map<View,CustomListAdapter> maps=new HashMap<View, CustomListAdapter>();
	private Map<View,CustomListView> mapList=new HashMap<View, CustomListView>();
	
	private EditText editInput_search;
	
	private final BeemRosterListener mBeemRosterListener = new BeemRosterListener();
	private IRoster mRoster;
	private DuitangInfoAdapter duitangInfoAdapter = null;//用户信息存入本地数据库
	private final IChatManagerListener mChatManagerListener = new ChatManagerListener();
	private IChatManager mChatManager;
	private IChat mChat;
	private String jid = "";
	private SatelliteMenu menu;
	private List<SatelliteMenuItem> items;
	private BaseDialog mBaseDialog;
	
    private final GreetListOnClick mOnGreetClick = new GreetListOnClick();//单击某招呼消息
    private final MyOnRefreshListener2 myOnRefreshListener2 = new MyOnRefreshListener2();
    private final GreetListOnLongClick mGreetLongClick = new GreetListOnLongClick();
    
	//处理 greetinfos 20141102 start
	private GreetInfoAdapter greetInfoAdapter = null;
	private static int greetPageSize = 10;//每页显示条数
	private List<GreetInfo> list_greetinfos = null;
	private int greetCurrentPage = 0;//当前页码 
	private int greetTotalCount;//总记录条数
	private int greetPageCount;//总页数
	//处理greetinfos 20141102 end
	
	private TContactGroupAdapter tContactGroupAdapter = null;
    
    public void onCreate(Bundle savedInstanceState) {
//    	VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
//    	VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.activity_contactframe);
    	mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
    	
		mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
//		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//		mHeaderLayout.setTitleRightImageButton("联系人列表", null,
//				R.drawable.refresh2,
//				new OnRightImageButtonClickListener());
		
		mHeaderLayout.init(HeaderStyle.TITLE_CONTACTLIST);
		mHeaderLayout.setTitleContactList(R.drawable.ic_chat_dis_1,
				R.drawable.bg_chat_dis_active, 
				"好友列表", "招呼盒子",
				R.drawable.refresh2,new OnMiddleImageButtonClickListener(),
				"好友", "招呼", new OnSwitcherButtonClickListener());
		
        xListViewHeader = (XListViewHeader)findViewById(R.id.xlistview_header);
        xListViewHeader.setVisiableHeight(60);
        xListViewHeader.setState(0);
        xListViewHeader.setVisibility(View.VISIBLE);
        
        
        mImageFetcher = new ImageFetcher(this, 240);
        mImageFetcher.setUListype(0);////0普通图片listview 1瀑布流  2地图模式
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
        
        itemWidth = this.getWindowManager().getDefaultDisplay().getWidth() / column_count;// 根据屏幕大小计算每列宽度
        
        editInput_search = (EditText)findViewById(R.id.editInput_search);
        editInput_search.addTextChangedListener(new watcher());
        init();
        
//        initRefreshView(linkedList);
        mAdapter = new CustomListAdapter(this, linkedList);
		
        contactListsFragment.setOnContactClick(mOnContactClick);
        contactListsFragment.setMyOnRefreshListener2(myOnRefreshListener2);
        contactListsFragment.setAdapter(mAdapter);
        
        greetInfosFragment.setOnGreetClick(mOnGreetClick);
        greetInfosFragment.setOnGreetLongClick(mGreetLongClick);
        greetInfosFragment.setMyOnRefreshListener2(myOnRefreshListener2);
        greetInfosFragment.setAdapter(mAdapter);
        
//    	btn = (Button)findViewById(R.id.button1);
//        btn.setOnClickListener(mOkListener);
//        udidTextView = (TextView)findViewById(R.id.udid_name);
        mContext = this;
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
	    
	    
	    
        menu = (SatelliteMenu) findViewById(R.id.menu);
        
        
//      List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>();
      items = new ArrayList<SatelliteMenuItem>();
      items.add(new SatelliteMenuItem(1, R.drawable.sat_item));//advancedsearch ic_1
      items.add(new SatelliteMenuItem(3, R.drawable.ic_3));//muc create
      items.add(new SatelliteMenuItem(4, R.drawable.ic_1));//exit sat_item
      items.add(new SatelliteMenuItem(5, R.drawable.ic_5));//nearby search
      items.add(new SatelliteMenuItem(6, R.drawable.ic_6));//? add a contact
      items.add(new SatelliteMenuItem(2, R.drawable.ic_2));//setting
      menu.addItems(items);        
      
      menu.setOnItemClickedListener(new SateliteClickedListener() {
			Intent intent;
			public void eventOccured(int id) {
				Log.i("sat", "Clicked on " + id);
				switch(id){
				    case 5:
//				    	showCustomToast("功能建设中...");
				    	
				    	intent =  new Intent(ContactFrameActivity.this, GpsSearchResPullRefListActivity.class);
						startActivity(intent);
				    	break;
				    case 2:
//						mBaseDialog = BaseDialog.getDialog(ContactFrameActivity.this, "安全退出", "您确定要退出应用吗?",
//								"确定", new DialogInterface.OnClickListener() {
//					
//									@Override
//									public void onClick(DialogInterface dialog, int which) {
//										dialog.dismiss();
//										
//										XmppConnectionAdapter.isPause = true;
//										XmppConnectionAdapter.isReconnectFlag = false;
//										if(XmppConnectionAdapter.instance!=null)
//											XmppConnectionAdapter.instance.resetApplication();
//										XmppConnectionAdapter.instance = null;
//										stopService(SERVICE_INTENT);
//										finishNew();
//										(new DeviceUuidFactory2(mContext)).remove(mContext);//用户手动退出登录时，删除uuid记录，防止统一部手机上，使用不同账号登录时uuid重复问题
//										SpiceApplication.getInstance().exit();
//										BeemApplication.getInstance().exit();
//								        // 杀死该应用进程
//								        android.os.Process.killProcess(android.os.Process.myPid());
//								        System.exit(0);
//									}
//						},"取消", new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog, int which) {
//									dialog.dismiss();;
//							}
//						});
//						mBaseDialog.show();
						
						intent =  new Intent(ContactFrameActivity.this, PreferenceActivity.class);
						startActivity(intent);
				    	break;
					case 1://4
						intent =  new Intent(ContactFrameActivity.this, AttendanceActivity2.class);
						startActivity(intent);
						break;
					case 4://1
						intent =  new Intent(ContactFrameActivity.this, AdvancedSearch.class);
				    	intent.putExtra("myheadimg", "myheadimg");
				    	intent.putExtra("myusername","myusername");
						startActivity(intent);
						break;
					case 6:
//						showCustomToast("功能建设中...");
						intent = new Intent(ContactFrameActivity.this,OtherFeedListActivity.class);
						intent.putExtra("otherusername", CurrentUid);//StringUtils.parseName(ui.getJid())
						intent.putExtra("myjid", CurrentUid);
						intent.putExtra("mtype", "1");
						startActivity(intent);
						break;
					case 3://GroupPickContactsActivity
						intent = new Intent(ContactFrameActivity.this, MucCreateActivity.class);//ContactListPullRefListActivity  MucCreateActivity GroupNew2Activity
//						intent.putExtra("friends", (Serializable)cGroups);
//						intent.putExtra("friends", (Serializable)cGroups);
						intent.putExtra("CurrentUid", CurrentUid);
						intent.putExtra("CurrentName", CurrentName);
						intent.putExtra("CurrentAvatarpath", CurrentAvatarpath);
						startActivity(intent);
						break;
					default:
						break;
				}
			}
		});
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
        
        duitangInfoAdapter = DuitangInfoAdapter.getInstance(this);
        greetInfoAdapter = GreetInfoAdapter.getInstance(this);
        tContactGroupAdapter = TContactGroupAdapter.getInstance(this);
        
        /**加载前先显示缓存数据(本地sqlite中存储的好友及群组列表)start*/
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
	    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
        try{
        	ContactGroup temp = null;
	        List<ContactGroup> list_ContactGroup = tContactGroupAdapter.getContactGroupsByPageIndex(1000, 0, login);
	        if(list_ContactGroup!=null && list_ContactGroup.size()!=0){
	            linkedList = new LinkedList(list_ContactGroup);
//	            for(int i=0;i<linkedList.size();i++){
//	            	temp = (ContactGroup)linkedList.get(i);
//	            	Log.e("MMMMMMMMMMMM20170815ContactFrameActivity(cache)MMMMMMMMMMMM", "++++++++++++++20170815ContactFrameActivity;temp.getUsername()="+temp.getUsername()+";login="+login);
//	            	if(temp.getUsername().equals(login))
//	            		linkedList.remove(i);
//	            }
	            parserData(0);
	        }
        }catch(Exception e){
        	e.printStackTrace();
        }
        /**加载前先显示缓存数据end*/
        SpiceApplication.getInstance().addActivity(this);
    	
//    	ObjectCache.saveStatus("isConnected", true, this);//标识为手动启动
    }
    public void preLoad(){//联网前先显示缓存/本地数据库内容
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
	    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
        try{
        	ContactGroup temp = null;
	        List<ContactGroup> list_ContactGroup = tContactGroupAdapter.getContactGroupsByPageIndex(1000, 0, login);
	        if(list_ContactGroup!=null && list_ContactGroup.size()!=0){
	            linkedList = new LinkedList(list_ContactGroup);
//	            for(int i=0;i<linkedList.size();i++){
//	            	temp = (ContactGroup)linkedList.get(i);
//	            	Log.e("MMMMMMMMMMMM20170815ContactFrameActivity(cache)MMMMMMMMMMMM", "++++++++++++++20170815ContactFrameActivity;temp.getUsername()="+temp.getUsername()+";login="+login);
//	            	if(temp.getUsername().equals(login))
//	            		linkedList.remove(i);
//	            }
	            parserData(0);
	        }
        }catch(Exception e){
        	e.printStackTrace();
        }
    }
	@Override
	protected void initViews() {
	}

	@Override
	protected void initEvents() {

	}
	protected void init() {
		Log.e("MMMMMMMMMMMM20141031ContactFrameActivity(init000)MMMMMMMMMMMM", "++++++++++++++20141031ContactFrameActivity(init000)");
		contactListsFragment = new ContactListsFragment(this, this);
		greetInfosFragment = new GreetInfosFragment(this, this);
		Log.e("MMMMMMMMMMMM20141031ContactFrameActivity(init444)MMMMMMMMMMMM", "++++++++++++++20141031ContactFrameActivity(init444)");
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.replace(R.id.contactframe_layout_content, contactListsFragment).commit();
//		mfgContent = contactListsFragment;//20150115
		Log.e("MMMMMMMMMMMM20141031ContactFrameActivity(init555)MMMMMMMMMMMM", "++++++++++++++20141031ContactFrameActivity(init555)");
//		ptrlv = contactListsFragment.ptrlv;
	}
	
	@Override
	public void onClick(View v) {
		//网络设置
		if(v.getId() == R.id.net_status_bar_btn){
			setNetworkMethod(this);
		}
	}
    //通知ContactListPullRefListActivity更新局部 消息图章为0，不显示消息图章
//	private String contactuserid = "";
	private String refreshlistviewonerow = "";
	private String refreshlistviewallrow = "";
    @Override
    protected void onResume() {
    	Log.e("================20170507 MainListActivity onResume================", "+++++++onResume+++++++");
		super.onResume();
		isWork = false;
        if(BeemConnectivity.isConnected(this)){
        	mNetErrorView.setVisibility(View.GONE);
        }else{
        	mNetErrorView.setVisibility(View.VISIBLE);
        }
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
		mImageFetcher.setExitTasksEarly(false);
		Log.e("================20170507 MainListActivity onResume 1111================", "+++++++onResume+++++++jid="+jid);
        if(jid!=null
        		&& jid.length()!=0
        		&& !jid.equalsIgnoreCase("null")
        		&& refreshlistviewonerow!=null
        		&& refreshlistviewonerow.length()!=0
        		&& !refreshlistviewonerow.equalsIgnoreCase("null")
        		&& refreshlistviewonerow.equals("1")){
        	Log.e("================20170507 MainListActivity onResume 2222================", "+++++++onResume+++++++jid="+jid);
        	//通知ContactListPullRefListActivity更新局部 消息图章为0，不显示消息图章
        	try{
    		    int index = mAdapter.containsKey(StringUtils.parseBareAddress(jid));
    		    Log.e("※※※※※####20170507MainListActivity####※※※※※", "※※index="+index);
    		    if(index!=-1){
    		    	updateUi4ptrlv((index+1),StringUtils.parseBareAddress(jid),true);
    		    }
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	// 下拉刷新:更新局部 消息图章,从其他页面比如ChatActivity返回本页面时
    		getContactList(ConstantValues.refresh);
        }
//		// 下拉刷新:更新局部 消息图章,从其他页面比如ChatActivity返回本页面时
//		getContactList(ConstantValues.refresh);
    }
    //SingleTask用此方法处理传过来的参数
    private String refreshroster = null;
    @Override
    protected void onNewIntent(Intent intent) {
    	Log.e("================20170507 MainListActivity onNewIntent================", "+++++++onNewIntent+++++++");
            super.onNewIntent(intent);

	        mImageFetcher.setExitTasksEarly(false);
            
            jid = intent.getStringExtra("jid");
            refreshlistviewonerow = intent.getStringExtra("refreshlistviewonerow");
            Log.e("================20170507 MainListActivity onNewIntent================", "+++++++onNewIntent+++++++jid="+jid); 
            refreshroster = intent.getStringExtra("refreshroster"); 
            if(refreshroster!=null
            		&& !refreshroster.equalsIgnoreCase("null")
            		&& refreshroster.length()!=0
            		&& refreshroster.equalsIgnoreCase("truezhiding")){
//            	flag = true;
//    			getContactList(ConstantValues.refresh);
//            	showCustomToast("置顶开始!"+refreshroster);
            	
            	Message load = mHandler.obtainMessage(ZHIDING_ROSTER_FINISH, null);
    			mHandler.sendMessage(load);
            }
    }
    public void onPause() {
    	super.onPause();
    	mImageFetcher.setExitTasksEarly(true);
    	Log.e("================2015 TestActivity.java ================", "++++++++++++++onPause()++++++++++++++mBinded="+mBinded);
//		if (mBinded) {
//			unbindService(mServConn);
//			mBinded = false;
//		}
    }
    /**
     * 重写finish()方法
     */
    @Override
    public void finish() {
        //super.finish(); //记住不要执行此句
        moveTaskToBack(true); //设置该activity永不过期，即不执行onDestroy()
    }   
 
    public void finishNew() {
        super.finish(); //记住要执行此句
        moveTaskToBack(false);
    }
    @Override
    protected void onDestroy() {
		super.onDestroy();
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()000++++++++++++++mBinded="+mBinded);
		mImageFetcher.onCancel();
		clearAsyncTask();
    	Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()111++++++++++++++");
// 	    XmppConnectionAdapter.isPause = true;
//		if(XmppConnectionAdapter.instance!=null)
//			XmppConnectionAdapter.instance.resetApplication();
//		XmppConnectionAdapter.instance = null;
//		stopService(SERVICE_INTENT);
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()222++++++++++++++");
//		loadingView.isStop = true;
		
		try {
		    if (mRoster != null) {
			mRoster.removeRosterListener(mBeemRosterListener);
			mRoster = null;
		    }
		} catch (RemoteException e) {
		    Log.d("ContactList", "Remote exception", e);
		}
	    if(mChatManager!=null)
	    	try{
	    	mChatManager.removeChatCreationListener(mChatManagerListener);
	    	}catch(RemoteException e){
	    		e.printStackTrace();
	    	}
	    try{
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}

		mXmppFacade = null;
		mChatManager = null;
		mRoster = null;
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		
		SpiceApplication.getInstance().exit();
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()333++++++++++++++");
    }
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(ContactFrameActivity.this);
		    		
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
//		    	getContactList();
//		    	getData(0);
		    	getContactList(0);
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			if(mRoster!=null)
			    try {
			    	mRoster.removeRosterListener(mBeemRosterListener);
			    } catch (RemoteException e) {
				e.printStackTrace();
			    }
		    try{
			    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
			    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
		    }catch (RemoteException e) {
		    	e.printStackTrace();
		    }
		    if(mChatManager!=null)
		    	try{
		    	mChatManager.removeChatCreationListener(mChatManagerListener);
		    	}catch(RemoteException e){
		    		e.printStackTrace();
		    	}
		    mXmppFacade = null;
		    mChatManager = null;
		    mRoster = null;
		    mBinded = false;
		}
    }
//    private List<Contact> mListContact;
    private LinkedList linkedList = new LinkedList();
    List<ContactGroup> cGroups = null;
	private String searchkey = "";
	private String searchtype = "0";
	private String ages = "12";
	private String genders = "1";
	private String distances = "5000";
	private String online = "0";
	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"请求异常,稍候重试!"};
	private int errorType = 5;
    private int currentPage = 0;
    private int numberresult = 50;
    private HashMap UnReadMsgNumberMap = new HashMap();
    private String CurrentUid = "";
    private String CurrentName = "";
    private String CurrentAvatarpath = "";
	public boolean initContactList(){
		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()111++++++++++++++");
		UnReadMsgNumberMap.clear();
		if(BeemConnectivity.isConnected( getApplicationContext())){
			Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()222++++++++++++++");
		    try {
		    	if(mXmppFacade!=null){
		    		mChatManager = mXmppFacade.getChatManager();
		    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()333++++++++++++++");
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
			    			){
			    		
//			    		ContactGroupListIQ reqXML = new ContactGroupListIQ();
//			            reqXML.setId("1234567890");
//			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
//			            reqXML.setUid("2");//2
//			            reqXML.setPage("0");
//			            reqXML.setGroupstr("1");
//			            reqXML.setSearchkey(searchkey);//searchkey
//			            reqXML.setView("me");
//			            reqXML.setFieldid("0");
//			            reqXML.setOrderby("threadnum");
//			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this);
//			            reqXML.setUuid(uuid);
////			            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
//			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ "me"+"threadnum"+uuid;
//			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
//			            reqXML.setHashcode(hash_dest);
//			            reqXML.setType(IQ.Type.SET);
//			            String elementName = "contactgrouplistiq"; 
//			    		String namespace = "com:isharemessage:contactgrouplistiq";
//			    		ContactGroupListIQResponseProvider provider = new ContactGroupListIQResponseProvider();
//			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "contactgrouplistiq", "com:isharemessage:contactgrouplistiq", provider);
//			            
//			            if(rt!=null){
//			                if (rt instanceof ContactGroupListIQResponse) {
//			                	final ContactGroupListIQResponse contactGroupListIQResponse = (ContactGroupListIQResponse) rt;
//
//			                    if (contactGroupListIQResponse.getChildElementXML().contains(
//			                            "com:isharemessage:contactgrouplistiq")) {
////			    					MainActivity.this.runOnUiThread(new Runnable() {
////				                    	
////            							@Override
////            							public void run() {
////            								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
////            							}
////            						});
//			                        String Id = contactGroupListIQResponse.getId();
//			                        String Apikey = contactGroupListIQResponse.getApikey();
//			                        ArrayList cGroups = contactGroupListIQResponse.getCGroups();
//			                        if(cGroups.size()!=0){
//				                        linkedList = new LinkedList(cGroups);
////			                        	for(int q=0;q<cGroups.size();q++){
////			                        		linkedList.add(cGroups.get(q));
////			                        	}
//				                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
//	//			                        mListContact = new ArrayList<Contact>(); 
//	//			                        for(int k=0;k<cGroups.size();k++){
//	//			                        	Log.e("响应packet结果解析...............", "cGroups"); 
//	////			                        	mListContact.add(contact);
//	//			                        }
//				                        cGroups = null;
//				                        return true;
//			                        }
//			                    }
//			                } 
//			            }
			    		
			    		CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
			            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
			            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
			            
			    		mRoster = mXmppFacade.getXmppConnectionAdapter().getRoster();
						if(mRoster != null){
						    try{
						    	mRoster.addRosterListener(mBeemRosterListener);
						    	Log.d("MainListActivity", "add roster listener");
						    }catch(Exception e){
						    }
//						    mChatManager = mXmppFacade.getChatManager();
//						    ((ChatManager)mChatManager).addChatListener(mChatListener);//用于更新消息图章
						    mChatManager.addChatCreationListener(mChatManagerListener);
						}
			    		cGroups = mRoster.getContactList();//List<ContactGroup> 
                        if(cGroups.size()!=0){
	                        linkedList = new LinkedList(cGroups);
//	                        tContactGroupAdapter.addTContactGroups(cGroups,StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID()));//好友及群组信息存储到本地
	                        tContactGroupAdapter.addTContactGroups(cGroups,StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID()));//好友及群组信息存储到本地
    						UnReadMsgNumber unReadMsgNumber = null;
    						ContactGroup contact = null;
    				        for (int i = 0; i < linkedList.size(); i++) {
    				        	contact = (ContactGroup)linkedList.get(i);
    				        	savePersonInfoToDB(contact);
    				        	unReadMsgNumber = duitangInfoAdapter.getUnReadMsgNumber(StringUtils.parseBareAddress(contact.getJID()));
    				        	if(unReadMsgNumber!=null){
    				        	
    				        		UnReadMsgNumberMap.put(unReadMsgNumber.getKey(),""+unReadMsgNumber.getUnreadnumber());
    				        	}else
    				        		UnReadMsgNumberMap.put(StringUtils.parseBareAddress(contact.getJID()), ""+0);
    				        }
//    				        mChat = ((BeemChatManager)mChatManager).getChat(contact);
//    				        if (mChat == null) {
//								Log.e("================20141027群聊multiUserChat20141027================", "群聊信息4");
////								if(mChatManager!=null)
//							    mChat = ((BeemChatManager)mChatManager).createChat(contact, null);//mMessageListener
////								if(mChat!=null)
//							}
//							mChat.addMessageListener(mMessageListener);
	                        cGroups = null;
	                        return true;
                        }
			    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()444++++++++++++++");

			    	    if(linkedList!=null && linkedList.size()!=0)
			    	    	errorType = 5;
			    	    else{
			    	    	if(linkedList!=null && linkedList.size()==0)
			    	    		errorType = 0;
			    	    	else
			    	    		errorType = 6;
			    	    }
						mBinded = true;//20130804 added by allen
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
				
		    } catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
	    }else{
	    	errorType = 4;
	    }
		return false;
	}
	private boolean flag = false;
//	private boolean isWork = false;
	private void getContactList(final int type) {
//		private View view2;
//		private int type2;
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
//				showLoadingDialog();
//				if(type==0){
//					showLoadingDialog();
//				}
				preLoad();//联网前先显示缓存/本地数据库内容 20200316 增加
				if(flag || (type==0)){
//					showLoadingDialog("正在加载,请稍后...");
					xListViewHeader.setShowText("正在加载,请稍候...");
					xListViewHeader.setVisibility(View.VISIBLE);
					xListViewHeader.setState(2);
				} else if(type!=0){
					xListViewHeader.setState(0);
					xListViewHeader.setVisibility(View.GONE);
				}
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				if(flagType)
					return initContactList();
				else
					return initGreetInfos();
//				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
//				if(type==0){
////					   view.findViewById(R.id.pb).setVisibility(View.GONE);
//					dismissLoadingDialog();
//				}
//				if(flag || (type==0)){
//					xListViewHeader.setState(0);
//					xListViewHeader.setVisibility(View.GONE);
//				}
//				if (!result) {
//					showCustomToast("数据加载失败...");
//					mHandler2.sendEmptyMessage(3);
//				} else {
//					mHandler2.sendEmptyMessage(0);
//				}
				if (result) {	
//					parserJsonData(result,type,view);
//					initRefreshView(linkedList);
					parserData(type);
//					getData(2);
//					Message load = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
//					mHandler.sendMessage(load);
					
//					Message refresh = mHandler.obtainMessage(REFRESH_DATA_FINISH,
//							tempList);
//					mHandler.sendMessage(refresh);
				}else{
					//提示没有获取到数据：可能网络问题
					mHandler.sendEmptyMessage(0);
				}
//				if(type==0){
//				   view.findViewById(R.id.pb).setVisibility(View.GONE);
//				}
				if(flag || (type==0)){
					xListViewHeader.setState(0);
					xListViewHeader.setVisibility(View.GONE);
				}
				flag = false;
				isWork = false;
			}

		});
		isWork = true;
		}
	}
	
	
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(ContactFrameActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(ContactFrameActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
//	Handler mHandler2 = new Handler() {
//
//		@Override
//		public void handleMessage(android.os.Message msg) {
//			super.handleMessage(msg);
//			switch (msg.what) {
//			case 0:
//				if(errorType==5 && linkedList!=null){
//					Contact contact = null;
//			        for (int i = 0; i < linkedList.size(); i++) {
//			        	contact = (Contact)mListContact.get(i);
//			        	Log.e("MMMMMMMMMMMM20140714(2)MMMMMMMMMMMM", "++++++++++++++"+contact.toString()+"++++++++++++");
//			        }
//				}else{
//		        	showCustomToast(errorMsg[errorType]);
//		        }
//				break;
//
//			case 1:
//				
//				showCustomToast("已达顶端!");
//				break;
//			case 2:
//				
//				showCustomToast("已达底端!");
//				break;
//			default:
//				
//				break;
//			}
//		}
//
//	};
    private class OkListener implements OnClickListener {
    	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.button1:
//				getContactList();
//				getData(0);
				getContactList(0);
				break;
			default:
				break;
			}
		}
    };
    
	@Override
	public void connectionStatusChanged(int connectedState, String reason) {
		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
		switch (connectedState) {
		case 0://connectionClosed
			mHandler3.sendEmptyMessage(0);
			break;
		case 1://connectionClosedOnError
//			mConnectErrorView.setVisibility(View.VISIBLE);
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接异常!");
			mHandler3.sendEmptyMessage(1);
			break;
		case 2://reconnectingIn
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接中...");
			mHandler3.sendEmptyMessage(2);
			break;
		case 3://reconnectionFailed
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("重连失败!");
			mHandler3.sendEmptyMessage(3);
			break;
		case 4://reconnectionSuccessful
//			mNetErrorView.setVisibility(View.GONE);
			mHandler3.sendEmptyMessage(4);

		default:
			break;
		}
	}
	Handler mHandler3 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				break;

			case 1:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接异常!");
				break;

			case 2:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接中...");
				break;
			case 3:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("重连失败!");
				break;
				
			case 4:
				mNetErrorView.setVisibility(View.GONE);
				String udid = "";
				String partnerid = "";
				try{
					udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
					partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
				}catch(Exception e){
					e.printStackTrace();
				}
//				udidTextView.setText("udid="+udid);
//				partneridEditText.setText(partnerid);
//				getContactList();//20141025 added by allen
				break;
			case 5:
				mNetErrorView.setVisibility(View.VISIBLE);
				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
				break;
			case 6:
				if(mXmppFacade!=null 
//						&& mXmppFacade.getXmppConnectionAdapter()!=null 
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
						&& BeemConnectivity.isConnected(mContext)){
					
				}else{
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("网络可用,连接中...");
				}
				break;	
			case 12:
				View view = ptrlv.getRefreshableView().getChildAt(msg.arg1);
				Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※view="+(view!=null));
				if(view!=null && flagType ){
					final ViewHolder holder = (ViewHolder) view.getTag();
					Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※holder="+(holder!=null));
					if(holder!=null){
						int num = msg.arg2;
						String username = (String)msg.obj;
						
						Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※num="+num);
						Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※username="+username);
						Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※htv_account="+holder.user_item_htv_account.getText());
						Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※username equal="+(holder.user_item_htv_account.getText().equals(username)));
		//				Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※text="+holder.badgeView.getText());
						if(num!=0){
							if(holder.user_item_htv_account.getText().equals(username)){
								final String s = String.valueOf(num);
		//						holder.badgeView.hide();
		//						holder.badgeView = new BadgeView(mContext, holder.user_item_relative);
								holder.badgeView.setText(s);
				        		holder.badgeView.show();
		//						holder.unreadmsgnumber.setVisibility(View.VISIBLE);
		//						holder.unreadmsgnumber.setText(s);
		//						holder.unreadmsgnumber.post(new Runnable(){
		//							public void run(){
		//								//settext
		//								holder.unreadmsgnumber.setVisibility(View.VISIBLE);
		//								holder.unreadmsgnumber.setText(s);
		//							}
		//						});
							}
						}else{
							if(holder.user_item_htv_account.getText().equals(username)){
								holder.badgeView.hide();
							}
						}
					}
				}
//				((StaggeredPullRefAdapter)ptrlv.getAdapter()).notifyDataSetChanged();
//				mAdapter.notifyDataSetChanged();
//				mAdapter.getSingleItem(username, String.valueOf(num));
//				mAdapter.notifyDataSetChanged();
				break;	
			}
		}

	};
	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();  
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
                Log.d("PoupWindowContactList", "网络状态已经改变");  
//                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//                info = connectivityManager.getActiveNetworkInfo();    
//                if(info != null && info.isAvailable()) {  
//                    String name = info.getTypeName();  
//                    Log.d(tag, "当前网络名称：" + name);  
//                    //doSomething()  
//                } else {  
//                    Log.d(tag, "没有可用网络");  
//                  //doSomething()  
//                }  
                if(BeemConnectivity.isConnected(context)){
//                	mNetErrorView.setVisibility(View.GONE);
//                	isconnect = 0;
                	mHandler3.sendEmptyMessage(6);//4
                }else{
//                	mNetErrorView.setVisibility(View.VISIBLE);
//                	isconnect = 1;
                	mHandler3.sendEmptyMessage(5);
                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
                }
            } 
        }
	};
	
	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
    /* 内部class继承PhoneStateListener */
    public class exPhoneCallListener extends PhoneStateListener
    {
        /* 重写onCallStateChanged
        当状态改变时改变myTextView1的文字及颜色 */
        public void onCallStateChanged(int state, String incomingNumber)
        {
          switch (state)
          {
            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
            case TelephonyManager.CALL_STATE_IDLE:
            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
            	if(phonestate){
            		onPhoneStateResume();
            	}
            	phonestate = false;
              break;
            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
            case TelephonyManager.CALL_STATE_OFFHOOK:
            	Log.e("================20131216 接起电话时================", "接起电话时");
            	onPhoneStatePause();
            	phonestate = true;
              break;
            /* 电话进来时 :在通话的过程中*/
            case TelephonyManager.CALL_STATE_RINGING:
//              getContactPeople(incomingNumber);
            	Log.e("================20131216 电话进来时================", "电话进来时");
//            	onBackPressed();
            	onPhoneStatePause();
            	phonestate = true;
              break;
            default:
              break;
          }
          super.onCallStateChanged(state, incomingNumber);
        }
    }
    
    protected void onPhoneStatePause() {
//		super.onPause();
    	try{
    		try {
    		    if (mRoster != null) {
    			mRoster.removeRosterListener(mBeemRosterListener);
    			mRoster = null;
    		    }
    		} catch (RemoteException e) {
    		    Log.d("ContactList", "Remote exception", e);
    		}
			if (mBinded) {
				getApplicationContext().unbindService(mServConn);
			    mBinded = false;
			}
			mXmppFacade = null;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    protected void onPhoneStateResume() {
//		super.onResume();
    	try{
		if (!mBinded){
//		    new Thread()
//		    {
//		        @Override
//		        public void run()
//		        {
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//		        }
//		    }.start();		    
		}
		if (mBinded){
			mImageFetcher.setExitTasksEarly(false);
		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    /*
     * 打开设置网络界面
     * */
    public static void setNetworkMethod(final Context context){
        //提示对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent=null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    intent = new Intent();
                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                }
                context.startActivity(intent);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).show();
    }
    
    

	/**
	 * ListView数据适配器
	 * @author Administrator
	 *  
	 */
	public class CustomListAdapter extends BaseAdapter implements Filterable, RecyclerListener{

		private LayoutInflater mInflater;
		public LinkedList<ContactGroup> mList;
		
		private LinkedList<GreetInfo> mGreetInfos;//处理 greetinfos 20141102
        public void clearGreetInfos(){
        	mGreetInfos.clear();
        }
	    private LinkedList<ContactGroup> mOriginalValues;
	    private final Object mLock = new Object();
	    private MyFilter myFilter;

		public CustomListAdapter(Context pContext, LinkedList<ContactGroup> pList) {
			mInflater = LayoutInflater.from(pContext);
			if(pList != null){
				mList = pList;
			}else{
				mList = new LinkedList<ContactGroup>();
			}
			mGreetInfos = new LinkedList<GreetInfo>();//处理 greetinfos 20141102
		}
		
		@Override
		public int getCount() {
//			return mList.size();
			if(flagType)
        		return mList.size();
        	else
        		return mGreetInfos.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
        public void addItemLast(List<ContactGroup> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 1 ");
        	if(datas!=null){
        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 2 ");
            	for (ContactGroup info : datas) {
            		mList.add(info);
            		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 3 ");
                }
        	}
        }
        public void addItemFirst_refresh_roster(List<ContactGroup> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 1 ");
        	if(datas!=null){
//        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 2 ");
            	for (ContactGroup info : datas) {
            		mList.addFirst(info);
            		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 3 ");
                }
        	}
        }
        public void addItemLast_refresh_roster(List<ContactGroup> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 1 ");
        	if(datas!=null){
//        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 2 ");
            	for (ContactGroup info : datas) {
            		mList.add(info);
            		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 3 ");
                }
        	}
        }
        public void delItemLast_refresh_roster(List<ContactGroup> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter delItemLast_refresh_roster 1 ");
        	int idx = -1;
        	if(datas!=null){
//        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter delItemLast_refresh_roster 2 ");
            	for (ContactGroup info : datas) {
            		idx = containsKey(StringUtils.parseBareAddress(info.getJID()));
            		if(idx!=-1)
//            			mList.remove(info);
            			mList.remove(idx);
            		Log.d("ContactFrameActivity", "CustomListAdapter delItemLast_refresh_roster 3 ");
                }
        	}
        }
        public void updateItemLast_refresh_roster(List<ContactGroup> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter updateItemLast_refresh_roster 1 ");
        	int idx = -1;
        	if(datas!=null){
//        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter updateItemLast_refresh_roster 2 ");
//        		//方法一:bug java.util.ConcurrentModificationException
//            	for (ContactGroup info : datas) {
//            		idx = containsKey(StringUtils.parseBareAddress(info.getJID()));
//            		if(idx!=-1){
////            			mList.remove(info);
//            			mList.remove(idx);
//            			mList.add(info);
//            		}
//            		Log.d("ContactFrameActivity", "CustomListAdapter updateItemLast_refresh_roster 3 ");
//                }
//            	//方法二：bug java.util.ConcurrentModificationException
//            	Iterator<ContactGroup> it = datas.iterator();
//            	ContactGroup info = null;
//            	while (it.hasNext()) {
//            		info = it.next();
//            		idx = containsKey(StringUtils.parseBareAddress(info.getJID()));
//            		if(idx!=-1){
////            			mList.remove(info);
//            			mList.remove(idx);
//            			mList.add(info);
//            		}
//            		Log.d("ContactFrameActivity", "CustomListAdapter updateItemLast_refresh_roster 3 ");
//            	}
            	//方法三：
            	ContactGroup info2 = null;
            	for(int i=0;i<datas.size();i++){
            		info2 = datas.get(i);
            		idx = containsKey(StringUtils.parseBareAddress(info2.getJID()));
            		if(idx!=-1){
//            			mList.remove(info);
            			mList.remove(idx);
            			mList.add(info2);
            			
            		}
            		Log.d("ContactFrameActivity", "CustomListAdapter updateItemLast_refresh_roster 3 ");
            	}
        	}
        }
        public void addItemLastGreetInfos(List<GreetInfo> datas) {
        	if(datas!=null){
        		mGreetInfos.clear();
//        		notifyDataSetInvalidated(); 
            	for (GreetInfo info : datas) {
            		mGreetInfos.add(info);
                }
        	}
        }
        public void addItemTopGreetInfos(List<GreetInfo> datas) {
            if(datas!=null){
            	mGreetInfos.clear();
	        	for (GreetInfo info : datas) {
	        		mGreetInfos.add(info);
	            }
            }
        }
        public int containsKey(String key){
        	int i = 0;
        		Iterator<ContactGroup> it = mList.iterator();
        		ContactGroup di;
        		while(it.hasNext()){
        			di = it.next();
        			
        		    if(StringUtils.parseBareAddress(di.getJID()).equals(key))
//        			if(di.getJID().equals(key))
        		    	return i;
        		    i++;
        		}
        	return -1;
        }

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (getCount() == 0) {
				return null;
			}
			ViewHolder holder = null;
			ViewHolderGreetInfo holderGreetInfo = null;
			if(flagType){
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.listitem_contacts, null);

				holder = new ViewHolder();
				holder.imageView = (ImageView)convertView.findViewById(R.id.news_pic);
//				holder.mTitle = (TextView) convertView.findViewById(R.id.news_title);
//				holder.mContent = (TextView) convertView.findViewById(R.id.news_content);
//				holder.mGentie=(TextView) convertView.findViewById(R.id.news_gentiecount);
				holder.contentView = (HandyTextView) convertView.findViewById(R.id.user_item_htv_name);//昵称
                holder.user_item_layout_gender = (LinearLayout)convertView.findViewById(R.id.user_item_layout_gender);
                holder.user_item_iv_gender = (ImageView)convertView.findViewById(R.id.user_item_iv_gender);
                holder.user_item_htv_age = (HandyTextView)convertView.findViewById(R.id.user_item_htv_age);
                
                holder.user_item_htv_account = (HandyTextView)convertView.findViewById(R.id.user_item_htv_account);//帐号
                holder.user_item_htv_sign = (HandyTextView)convertView.findViewById(R.id.user_item_htv_sign);//个性签名
                holder.user_item_iv_icon_group_role = (ImageView)convertView.findViewById(R.id.user_item_iv_icon_group_role);
                holder.user_item_relative = (RelativeLayout)convertView.findViewById(R.id.user_item_relative);
                holder.badgeView = new BadgeView(mContext, holder.user_item_relative);
                holder.unreadmsgnumber = (TextView)convertView.findViewById(R.id.unreadmsgnumber);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			ContactGroup detail=mList.get(position);
//            holder.mTitle.setText(detail.getTitle());
//            holder.mContent.setText(detail.getContent());
//            holder.mGentie.setText(detail.getGentiecount()+"跟帖");
			int cgrouptype = detail.getType();////0 contact,1 group
			String s1 = "";
			final String username;
			final String tagid;
			final String tagname;
			final String tagimg;
			switch(cgrouptype){
				case 0:
					if(detail.getName()!=null
							&& !detail.getName().equalsIgnoreCase("null")
							&& detail.getName().length()!=0)
						holder.contentView.setText(detail.getName());
					else
						holder.contentView.setText(detail.getUsername());
					username = detail.getUsername();
////					holder.imageView.set_url(detail.getAvatarPath());
//					holder.imageView.setTagid(null);//holder复用，防止数据重复
//					holder.imageView.setTagname(null);
//					holder.imageView.setTagimg(null);
//					holder.imageView.setUsername(detail.getUsername());
////					holder.user_item_htv_account.setText(detail.getUsername());
					holder.user_item_htv_account.setText(StringUtils.parseBareAddress(detail.getJID()));
		            holder.user_item_htv_sign.setText(detail.getNote());
		            
	            	if(detail.getSex()==1){//0 默认未知，1男，2女
	            		holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_male);
	            		holder.user_item_iv_gender.setImageResource(R.drawable.ic_user_male);
	            	}else{
	            		holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_famal);
	            		holder.user_item_iv_gender.setImageResource(R.drawable.ic_user_famale);
	            	}
	            	holder.user_item_iv_icon_group_role.setVisibility(View.GONE);
	            	int age = 0;
	                if(detail.getBirthyear()!=null
	                		&& !detail.getBirthyear().equalsIgnoreCase("null")
	                		&& detail.getBirthyear().length()!=0
	                		&& detail.getBirthmonth()!=null
	                		&& !detail.getBirthmonth().equalsIgnoreCase("null")
	                		&& detail.getBirthmonth().length()!=0
	                		&& detail.getBirthday()!=null
	                		&& !detail.getBirthday().equalsIgnoreCase("null")
	                		&& detail.getBirthday().length()!=0){
	                	
	                	try{
	                		age = TextUtils.getAge(Integer.parseInt(detail.getBirthyear()),
	                				Integer.parseInt(detail.getBirthmonth()),
	                				Integer.parseInt(detail.getBirthday()));
	                	}catch(Exception e){
	                		e.printStackTrace();
	                		age = 0;
	                	}
	                }
	                if(age>200)
	                	holder.user_item_htv_age.setText("未知");
	                else
	                	holder.user_item_htv_age.setText(age+"");
	                
	                s1 = detail.getAvatarPath();
	                int idx = s1.indexOf("/data/avatar/");
	        		String path = "";
	        		if(idx!=-1){
	        			path = s1.substring(idx+1);
	        		}
	        		try{
	        			path = "data/avatar/"+avatar_file(Integer.parseInt(detail.getUid()),"middle","");
	        		}catch(Exception e){
	        			e.printStackTrace();
	        		}
//	        		mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+path, holder.imageView);
//	        		mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+s1, holder.imageView);
	        		holder.imageView.setOnClickListener(new OnClickListener(){
	        			@Override
	        			public void onClick(View v) {
	        				Intent intent = new Intent(mContext, OtherProfileActivity.class);
	        	        	intent.putExtra("searchkey",username);
	        	        	mContext.startActivity(intent);
	        			}
	        		});
//	        		ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+s1, holder.imageView,SpiceApplication.getInstance().getWholeOptions());
	        		ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+s1, holder.imageView,SpiceApplication.getInstance().getWholeOptions());
					break;
				case 1:
					if(detail.getTagname()!=null
							&& !detail.getTagname().equalsIgnoreCase("null")
							&& detail.getTagname().length()!=0)
						holder.contentView.setText(detail.getTagname());
					else
						holder.contentView.setText(detail.getTagid());
////					holder.imageView.set_url(detail.getPic());
//					holder.imageView.setTagid(detail.getTagid());
//					holder.imageView.setTagname(detail.getTagname());
//					holder.imageView.setTagimg(detail.getPic());
//					holder.imageView.setUsername(null);
////					holder.user_item_htv_account.setText(detail.getTagid());
					tagid = detail.getTagid();
					tagname = detail.getTagname();
					tagimg = detail.getPic();
					holder.user_item_htv_account.setText(StringUtils.parseBareAddress(detail.getJID()));
					if(detail.getSubject()!=null
							&& !detail.getSubject().equalsIgnoreCase("null")
							&& detail.getSubject().length()!=0)
						holder.user_item_htv_sign.setText(detail.getSubject());
					else
						holder.user_item_htv_sign.setText("");
		            holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_grouplist_ower);
	        		holder.user_item_iv_gender.setImageResource(R.drawable.ic_userinfo_group4);
	        		holder.user_item_iv_icon_group_role.setVisibility(View.VISIBLE);
	        		holder.user_item_htv_age.setText("群组");
//	        		mImageFetcher.loadImage(detail.getPic().replace("localhost", "10.0.2.2"), holder.imageView);
//	        		mImageFetcher.loadImage(detail.getPic().replace(, "10.0.2.2"), holder.imageView);
//	        		mImageFetcher.loadImage(detail.getPic().replace("http://localhost:8080/javacenterhome/", XmppConnectionAdapter.downloadPrefix), holder.imageView);
	        		holder.imageView.setOnClickListener(new OnClickListener(){
	        			@Override
	        			public void onClick(View v) {
	                    	Intent intent = new Intent(mContext, GroupDetailsActivity.class);//GroupProfileActivity.class multiuserlistmain.class
//	                    	Toast.makeText(context, "单击roomname：" + StringUtils.parseName(get_url()), Toast.LENGTH_SHORT).show();
	                    	intent.putExtra("groupId", tagid);
	                    	intent.putExtra("groupName",tagname);
	                    	intent.putExtra("tagimg", tagimg);
	                    	mContext.startActivity(intent);
	        			}
	        		});
//	        		ImageLoader.getInstance().displayImage(detail.getPic().replace("http://localhost:8080/javacenterhome/", XmppConnectionAdapter.downloadPrefix), holder.imageView,SpiceApplication.getInstance().getWholeOptions());
	        		ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+detail.getPic(), holder.imageView,SpiceApplication.getInstance().getWholeOptions());
	        		break;
				default:
					break;
			}
//			holder.contentView.setText(detail.getName()+detail.getTagname()+detail.getTagid()+detail.getUid());
            
            //设置图片
          /*  try{
            	File file=new File(Environment.getExternalStorageDirectory()+"/chinanews",detail.getTitle());
            	if(file.exists()&&file.length()>0){
            		holder.mImage.setImageURI(Uri.fromFile(file));
            	}else{
            		//去下载
            		Bitmap bitmap=HttpConnect.getImage(detail.getPicpath(), detail.getTitle());
            		holder.mImage.setImageBitmap(bitmap);
            	}
            }catch(Exception e){
            	
            }*/
//			mImageFetcher.loadImage(detail.getPic(), holder.imageView);
            Object num = UnReadMsgNumberMap.get(StringUtils.parseBareAddress(detail.getJID()));
            int unreadnum = 0;
            if(num!=null){
            	try{
            		unreadnum = Integer.parseInt((String)num);
            	}catch(Exception e){
            		unreadnum = 0;
            	}
            }
            if(unreadnum!=0){
	            holder.badgeView.setText(""+unreadnum);
	            holder.badgeView.show();
//	            holder.unreadmsgnumber.setVisibility(View.VISIBLE);
//	            holder.unreadmsgnumber.setText(""+unreadnum);
            }else{
            	holder.badgeView.hide();
//            	holder.unreadmsgnumber.setVisibility(View.GONE);
            }
			}else{
				//处理 greetinfos 20141102 start
            	GreetInfo greetInfo = mGreetInfos.get(position);
            	
//            	if(convertView!=null){
//            		if(convertView.getTag() instanceof ViewHolderGreetInfo)
//            			;
//            		else
//            			convertView = null;
//            	}
            	
            	if (convertView == null) {
                    LayoutInflater layoutInflator = LayoutInflater.from(parent.getContext());
                    convertView = layoutInflator.inflate(R.layout.listitem_greetinfo, null);//listitem_user
                    holderGreetInfo = new ViewHolderGreetInfo();
                    holderGreetInfo.greetinfo_item_type_icon = (ImageView)convertView.findViewById(R.id.greetinfo_item_type_icon);
                    holderGreetInfo.user_item_htv_account = (HandyTextView)convertView.findViewById(R.id.user_item_htv_account);//发送人
                    holderGreetInfo.user_item_htv_time = (HandyTextView)convertView.findViewById(R.id.user_item_htv_time);//接收时间
                    holderGreetInfo.user_item_htv_content = (HandyTextView)convertView.findViewById(R.id.user_item_htv_content);
                    convertView.setTag(holderGreetInfo);
            	}else
            		holderGreetInfo = (ViewHolderGreetInfo) convertView.getTag();
            	
            	switch(greetInfo.getMtype()){
	            	case 100://加好友请求
	            		holderGreetInfo.greetinfo_item_type_icon.setImageResource(R.drawable.addfriend);
	            		if(greetInfo.getMfrom().indexOf("@")!=-1)
	            			holderGreetInfo.user_item_htv_account.setText(StringUtils.parseName(greetInfo.getMfrom()));
	            		else
	            			holderGreetInfo.user_item_htv_account.setText(greetInfo.getMfrom());
	            		holderGreetInfo.user_item_htv_time.setText(greetInfo.getMtimestamp().toLocaleString());
	            		if(greetInfo.getMfrom().indexOf("@")!=-1)
	            			holderGreetInfo.user_item_htv_content.setText("[好友邀请]"+StringUtils.parseName(greetInfo.getMfrom())+"想加你为好友,你是否同意?");
	            		else
	            			holderGreetInfo.user_item_htv_content.setText("[好友邀请]"+greetInfo.getMfrom()+"想加你为好友,你是否同意?");
	            		break;
	            	case 200://群邀请
	            		holderGreetInfo.greetinfo_item_type_icon.setImageResource(R.drawable.addroomuser);
	            		if(greetInfo.getMfrom().indexOf("@")!=-1)
	            			holderGreetInfo.user_item_htv_account.setText(StringUtils.parseName(greetInfo.getMfrom()));
	            		else
	            			holderGreetInfo.user_item_htv_account.setText(greetInfo.getMfrom());
	            		holderGreetInfo.user_item_htv_time.setText(greetInfo.getMtimestamp().toLocaleString());
	            		if(greetInfo.getMfrom().indexOf("@")!=-1)
	            			holderGreetInfo.user_item_htv_content.setText("[群组邀请]"+StringUtils.parseName(greetInfo.getMfrom())+"想邀请你加入群,你是否同意?");
	            		else
	            			holderGreetInfo.user_item_htv_content.setText("[群组邀请]"+greetInfo.getMfrom()+"想邀请你加入群,你是否同意?");
	            		break;
	            	case 300://系统消息
	            		holderGreetInfo.greetinfo_item_type_icon.setImageResource(R.drawable.sysmsg);
	            		holderGreetInfo.user_item_htv_account.setText(greetInfo.getMfrom());
	            		holderGreetInfo.user_item_htv_time.setText(greetInfo.getMtimestamp().toLocaleString());
//	            		holderGreetInfo.user_item_htv_content.setText("[系统消息]"+greetInfo.getMadminmsgtitle()+" : "+greetInfo.getMadminmsgbody());
	            		holderGreetInfo.user_item_htv_content.setText("[系统消息]"+greetInfo.getMadminmsgtitle());
	            		break;	
	            	case 400://普通陌生人message消息
//	            		Toast.makeText(mContext, "普通陌生消息:"+greetInfo.toString(), Toast.LENGTH_SHORT).show(); 
	            		holderGreetInfo.greetinfo_item_type_icon.setImageResource(R.drawable.normalmsg);
	            		if(greetInfo.getMfrom().indexOf("@")!=-1)
	            			holderGreetInfo.user_item_htv_account.setText(StringUtils.parseName(greetInfo.getMfrom()));
	            		else
	            			holderGreetInfo.user_item_htv_account.setText(greetInfo.getMfrom());
	            		holderGreetInfo.user_item_htv_time.setText(greetInfo.getMtimestamp().toLocaleString());
	            		
//	            		holderGreetInfo.user_item_htv_content.setText("[陌生消息]"+greetInfo.getMbody());
	            		if(greetInfo.getMfrom().indexOf("@")!=-1)
	            			holderGreetInfo.user_item_htv_content.setText("[好友邀请]"+StringUtils.parseName(greetInfo.getMfrom())+"想加你为好友,你是否同意?");
	            		else
	            			holderGreetInfo.user_item_htv_content.setText("[好友邀请]"+greetInfo.getMfrom()+"想加你为好友,你是否同意?");
	            		break;
	            	default:
	            		break;
            	}
			}
			return convertView;
		}
		
        /**
        249	     * 当列表单元滚动到可是区域外时清除掉已记录的图片视图
        250	     *
        251	     * @param view
        252	     */
        @Override
        public void onMovedToScrapHeap(View view) {
//        	if(flagType){
	            ViewHolder holder = (ViewHolder) view.getTag();
	//        	this.imageViews.remove(holder.avatar);
	//        	this.imageViews.remove(holder.picPhoto);
	            if(holder!=null && holder.imageView!=null){
//		            holder.imageView.recycle();//flowview时起作用
		            holder.imageView = null;
	            }
//        	}
        }
        
        @Override
        public Filter getFilter() {
           if (myFilter == null) {
              myFilter = new MyFilter();
           }
           return myFilter;
        }
        
        public class MyFilter extends Filter {
        	 
            @Override
            protected FilterResults performFiltering(CharSequence prefix) {
               // 持有过滤操作完成之后的数据。该数据包括过滤操作之后的数据的值以及数量。 count:数量 values包含过滤操作之后的数据的值
               FilterResults results = new FilterResults();
       
               if (mOriginalValues == null) {
                  synchronized (mLock) {
                      // 将list的用户 集合转换给这个原始数据的ArrayList
                      mOriginalValues = mList;
                  }
               }
               if (prefix == null || prefix.length() == 0) {
                  synchronized (mLock) {
                	  LinkedList<ContactGroup> list = mOriginalValues;
                      results.values = list;
                      results.count = list.size();
                  }
               } else {
                  // 做正式的筛选
                  String prefixString = prefix.toString().toLowerCase();
                  Pattern p = Pattern.compile(prefixString);
                  // 声明一个临时的集合对象 将原始数据赋给这个临时变量
                  final LinkedList<ContactGroup> values = mOriginalValues;
       
                  final int count = values.size();
       
                  // 新的集合对象
                  final LinkedList<ContactGroup> newValues = new LinkedList<ContactGroup>();
       
                  for (int i = 0; i < values.size(); i++) {
                      // 如果姓名的前缀相符或者电话相符就添加到新的集合
                      final ContactGroup info = (ContactGroup) values.get(i);
       
//                      Log.i("coder", "PinyinUtils.getAlpha(value.getUsername())"
//                            + PinyinUtils.getAlpha(value.getUsername()));
//                      if (PinyinUtils.getAlpha(value.getUsername()).startsWith(
//                            prefixString)
//                            || value.getPhonenum().startsWith(prefixString)||value.getUsername().startsWith(prefixString)) {
//       
//                         newValues.add(info);
//                      }
	      	            Matcher matcher = p.matcher(info.getName()+info.getUsername()+info.getTagname());
	    	            if(matcher.find()){
	    	            	newValues.add(info);
	    	            }
                  }
                  // 然后将这个新的集合数据赋给FilterResults对象
                  results.values = newValues;
                  results.count = newValues.size();
               }
       
               return results;
            }
       
            @Override
            protected void publishResults(CharSequence constraint,
                  FilterResults results) {
               // 重新将与适配器相关联的List重赋值一下
            	mList = (LinkedList<ContactGroup>) results.values;
               if (results.count > 0) {
                  notifyDataSetChanged();
               } else {
                  notifyDataSetInvalidated();
               }
            }
       
         }
	}
	private static class ViewHolder {
		private ImageView imageView;//FlowView
//		private TextView mTitle;
//		private TextView mContent;
//		private TextView mGentie;
		private HandyTextView contentView;
        TextView timeView;
        
        LinearLayout user_item_layout_gender;//20140731 added
        ImageView user_item_iv_gender;
        HandyTextView user_item_htv_age;
        
        HandyTextView user_item_htv_account;//帐号
        HandyTextView user_item_htv_sign;//个性签名
        
        ImageView user_item_iv_icon_group_role;
        
        RelativeLayout user_item_relative;
        
        BadgeView badgeView;
        TextView unreadmsgnumber;
	}
    class ViewHolderGreetInfo {
    	ImageView greetinfo_item_type_icon;
        HandyTextView user_item_htv_account;//发送人
        HandyTextView user_item_htv_time;//接收时间
        HandyTextView user_item_htv_content;
    }
	   class watcher implements TextWatcher{

	        @Override
	        public void afterTextChanged(Editable s) {
	            // TODO Auto-generated method stub
	            
	        }

	        @Override
	        public void beforeTextChanged(CharSequence s, int start, int count,
	                int after) {
	            // TODO Auto-generated method stub    
	            
	        }

	        @Override
	        public void onTextChanged(CharSequence s, int start, int before,
	                int count) {
	        	mAdapter.getFilter().filter(s.toString());
	        }
	        
	    }
	
	////////////////////////刷新部分数据//////////////////////////////////////
	private void initRefreshView(LinkedList<ContactGroup> mList){
		mAdapter = new CustomListAdapter(this, mList);
//		mListView = (CustomListView)this.findViewById(R.id.mListView);
//		mListView.setAdapter(mAdapter);
////		mListView.setOnClickListener();//
//		mListView.setOnItemClickListener(mOnContactClick);//
//		
////		CustomListAdapter adapter=maps.get(item);
////		CustomListView listView=mapList.get(item);
////		if(adapter==null){
////			maps.put(item, mAdapter);
////		}
////		if(listView==null){
////			mapList.put(item, mListView);
////		}
//
//		mListView.setOnRefreshListener(new OnRefreshListener() {
//			@Override
//			public void onRefresh() {
//				getContactList(ConstantValues.refresh);
////				getContactList();
//			}
//		});
//
//		mListView.setOnLoadListener(new OnLoadMoreListener() {
//			@Override
//			public void onLoadMore() {
//				getContactList(ConstantValues.load);
////				getContactList();
//			}
//		});
		
		ptrlv = (PullToRefreshListView) this.findViewById(R.id.ptrlvHeadLineNews);
        ptrlv.setOnItemClickListener(mOnContactClick);
//      ptrlv.setOnLongClickListener(mOnContactLongClick);
        ptrlv.setMode(Mode.BOTH);
        ptrlv.setOnRefreshListener(new MyOnRefreshListener2());
//      ptrlv.getRefreshableView().setRecyclerListener();
        ptrlv.setAdapter(mAdapter);
		
	}
	class MyOnRefreshListener2 implements OnRefreshListener2<ListView> {

//		private PullToRefreshListView mPtflv;

		public MyOnRefreshListener2() {
//			this.mPtflv = ptflv;
		}

		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			// 下拉刷新
			getContactList(ConstantValues.refresh);
		}

		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
			// 上拉加载
			getContactList(ConstantValues.load);
		}

	}
	
    public ContactGroup containsKey4ZhiDing(String key){
    		Iterator<ContactGroup> it = linkedList.iterator();
    		ContactGroup di;
    		while(it.hasNext()){
    			di = it.next();
    		    if(StringUtils.parseBareAddress(di.getJID()).equals(key))
    		    	return di;
    		}
    	return null;
    }
    
	private Handler mHandler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			if(flagType){
				switch (msg.what) {
					case 0:
						//没有获取到数据：可能网络问题
//						Toast.makeText(mContext, "没有获取到数据：可能网络问题", Toast.LENGTH_SHORT).show();
						ptrlv.onRefreshComplete();
						break;
					case REFRESH_DATA_FINISH:
						if(mAdapter!=null){
							List<ContactGroup> newNews=(List<ContactGroup>) msg.obj;
		//					for(ContactGroup news :newNews){
		//						mAdapter.mList.addFirst(news);
		//					}
							mAdapter.addItemLast(newNews);
							mAdapter.notifyDataSetChanged();
						}
						
						//判断置顶信息更新start
						SharedPreferences settings3 = PreferenceManager.getDefaultSharedPreferences(mContext);
						String zhiding_username3 = settings3.getString(SpiceApplication.ZHIDING_ACCOUNT_USERNAME_KEY, "");
						String[] arr3 = zhiding_username3.split("#");
//						showCustomToast("置顶barejid="+arr.length+";"+zhiding_username);
//						StringBuffer sb = new StringBuffer();
						List<ContactGroup> temp_zhingding3 = new LinkedList<ContactGroup>();
						ContactGroup t_zhiding3 = null;
						if(linkedList!=null && linkedList.size()!=0){
							for(int i=0;i<arr3.length;i++){
								if(arr3[i].length()!=0
										&& !arr3[i].equalsIgnoreCase("null")
										&& arr3[i]!=null){
//									sb.append("i="+i+";value="+arr[i]);
									t_zhiding3 = containsKey4ZhiDing(arr3[i]);
									if(t_zhiding3!=null)
										temp_zhingding3.add(t_zhiding3);
								}
							}
						}
						if(mAdapter!=null && temp_zhingding3.size()!=0){
							mAdapter.delItemLast_refresh_roster(temp_zhingding3);
							mAdapter.addItemFirst_refresh_roster(temp_zhingding3);
							mAdapter.notifyDataSetChanged();
						}
						//判断置顶信息更新end
		//				mListView.onRefreshComplete();	//下拉刷新完成
						ptrlv.onRefreshComplete();
						break;
					case LOAD_DATA_FINISH:
						if(mAdapter!=null){
		//					mAdapter.mList.addAll((LinkedList<ContactGroup>)msg.obj);
							List<ContactGroup> newNews=(List<ContactGroup>) msg.obj;
							mAdapter.addItemLast(newNews);
							mAdapter.notifyDataSetChanged();
						}
						
						//判断置顶信息更新start
						SharedPreferences settings2 = PreferenceManager.getDefaultSharedPreferences(mContext);
						String zhiding_username2 = settings2.getString(SpiceApplication.ZHIDING_ACCOUNT_USERNAME_KEY, "");
						String[] arr2 = zhiding_username2.split("#");
//						showCustomToast("置顶barejid="+arr.length+";"+zhiding_username);
//						StringBuffer sb = new StringBuffer();
						List<ContactGroup> temp_zhingding2 = new LinkedList<ContactGroup>();
						ContactGroup t_zhiding2 = null;
						if(linkedList!=null && linkedList.size()!=0){
							for(int i=0;i<arr2.length;i++){
								if(arr2[i].length()!=0
										&& !arr2[i].equalsIgnoreCase("null")
										&& arr2[i]!=null){
//									sb.append("i="+i+";value="+arr[i]);
									t_zhiding2 = containsKey4ZhiDing(arr2[i]);
									if(t_zhiding2!=null)
										temp_zhingding2.add(t_zhiding2);
								}
							}
						}
						if(mAdapter!=null && temp_zhingding2.size()!=0){
							mAdapter.delItemLast_refresh_roster(temp_zhingding2);
							mAdapter.addItemFirst_refresh_roster(temp_zhingding2);
							mAdapter.notifyDataSetChanged();
						}
						//判断置顶信息更新end
		//				mListView.onLoadMoreComplete();	//加载更多完成
						ptrlv.onRefreshComplete();
						break;
		//			case PIC:
		//				mViewPager.setCurrentItem(currentPosition);
		//				break;
					case REFRESH_ROSTER_FINISH:
						if(mAdapter!=null){
							List<ContactGroup> newNews=(List<ContactGroup>) msg.obj;
		//					for(ContactGroup news :newNews){
		//						mAdapter.mList.addFirst(news);
		//					}
							mAdapter.addItemLast_refresh_roster(newNews);
							mAdapter.notifyDataSetChanged();
						}
						
		//				mListView.onRefreshComplete();	//下拉刷新完成
						ptrlv.onRefreshComplete();
						break;
					case DELETE_ROSTER_FINISH:
						if(mAdapter!=null){
							List<ContactGroup> newNews=(List<ContactGroup>) msg.obj;
		//					for(ContactGroup news :newNews){
		//						mAdapter.mList.addFirst(news);
		//					}
							mAdapter.delItemLast_refresh_roster(newNews);
							mAdapter.notifyDataSetChanged();
						}
		//				mListView.onRefreshComplete();	//下拉刷新完成
						ptrlv.onRefreshComplete();
						break;
					case UPDATE_ROSTER_FINISH:
						if(mAdapter!=null){
							List<ContactGroup> newNews=(List<ContactGroup>) msg.obj;
		//					for(ContactGroup news :newNews){
		//						mAdapter.mList.addFirst(news);
		//					}
							mAdapter.updateItemLast_refresh_roster(newNews);
							mAdapter.notifyDataSetChanged();
						}
		//				mListView.onRefreshComplete();	//下拉刷新完成
						ptrlv.onRefreshComplete();
						break;		
					case ZHIDING_ROSTER_FINISH:
						SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
						String zhiding_username = settings.getString(SpiceApplication.ZHIDING_ACCOUNT_USERNAME_KEY, "");
						String[] arr = zhiding_username.split("#");
//						showCustomToast("置顶barejid="+arr.length+";"+zhiding_username);
//						StringBuffer sb = new StringBuffer();
						List<ContactGroup> temp_zhingding = new LinkedList<ContactGroup>();
						ContactGroup t_zhiding = null;
						if(linkedList!=null && linkedList.size()!=0){
							for(int i=0;i<arr.length;i++){
								if(arr[i].length()!=0
										&& !arr[i].equalsIgnoreCase("null")
										&& arr[i]!=null){
//									sb.append("i="+i+";value="+arr[i]);
									t_zhiding = containsKey4ZhiDing(arr[i]);
									if(t_zhiding!=null)
										temp_zhingding.add(t_zhiding);
								}
							}
						}
						if(mAdapter!=null){
							if(temp_zhingding.size()!=0){
								mAdapter.delItemLast_refresh_roster(temp_zhingding);
								mAdapter.addItemFirst_refresh_roster(temp_zhingding);
							}else
								mAdapter.addItemLast((List<ContactGroup>)linkedList);
							mAdapter.notifyDataSetChanged();
						}
						ptrlv.onRefreshComplete();
//						showCustomToast("置顶barejid="+sb.toString());
						break;
					default:
						break;
				}
			}else{
	    		if(list_greetinfos!=null && list_greetinfos.size()!=0){
	    			if(mType == 2)
						mAdapter.addItemLastGreetInfos(list_greetinfos);
					else if(mType == 1)
						mAdapter.addItemTopGreetInfos(list_greetinfos);
					else
						mAdapter.addItemLastGreetInfos(list_greetinfos);
		            
		            mAdapter.notifyDataSetChanged();
//		            list_greetinfos.clear();
		            
	    		}else{
	    			mAdapter.clearGreetInfos();
	    			mAdapter.notifyDataSetChanged();
	    			showCustomToast("暂无招呼消息。");
	    		}
	    		mType = 0;
	    		ptrlv.onRefreshComplete();
			}
		};
	};
	
	public void parserData(final int type) {
		// 去服务器去数据
//		refreshData(type);
		if(linkedList!=null && linkedList.size()!=0)
		switch (type) {
//		case 0:
//			initRefreshView(linkedList);
//			break;
		case 0:
			Message load0 = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
			mHandler.sendMessage(load0);
			break;
		case 1:
			Message refresh = mHandler.obtainMessage(REFRESH_DATA_FINISH,
					linkedList);
			mHandler.sendMessage(refresh);
			break;
		case 2:
			Message load = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
			mHandler.sendMessage(load);
			break;

		default:
			break;
		}
	}
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
			getContactList(ConstantValues.refresh);
		}
	}
	private class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {

		@Override
		public void onClick() {
			flag = true;
			mHandler.sendEmptyMessage(0);
			getContactList(ConstantValues.refresh);
		}
	}
	private boolean isWork = false;
	public class OnSwitcherButtonClickListener implements
	onSwitcherButtonClickListener {
	
		@Override
		public void onClick(SwitcherButtonState state) {
			if(!isWork){//20141120防止恶意切换
				isWork = true;
				FragmentTransaction ft = getSupportFragmentManager()
						.beginTransaction();
				ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
				switch (state) {
				case LEFT:
					
					mHeaderLayout.setDefaultTitle("好友列表",null);
					ft.replace(R.id.contactframe_layout_content, contactListsFragment).commit();
					Log.e("MMMMMMMMMMMMContactFrameActivity(switch111)MMMMMMMMMMMM", "++++++++++++++ContactFrameActivity(switch111)");
//					flagType = true;//true: contactlist false:greetInfos
					break;
			
				case RIGHT:
					
					mHeaderLayout.setDefaultTitle("招呼盒子",null);
					ft.replace(R.id.contactframe_layout_content, greetInfosFragment).commit();
					Log.e("MMMMMMMMMMMMContactFrameActivity(switch222)MMMMMMMMMMMM", "++++++++++++++ContactFrameActivity(switch222)");
//					flagType = false;//true: contactlist false:greetInfos
					break;
				}
				isWork = false;
			}
		}

	}
    //招呼盒子消息单击
    public class GreetListOnClick implements OnItemClickListener {//private
		/**
		 * Constructor.
		 */
		public GreetListOnClick( ) {
		}
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int pos, long lpos) {
			GreetInfo gi = list_greetinfos.get(pos-1);
			Intent intent = null;
			switch(gi.getMtype()){
				case 100://加好友请求
//					intent = new Intent(ContactFrameActivity.this, Subscription.class);
//					intent.setData(Contact.makeXmppUri(gi.getMfrom()));
//					intent.putExtra("greetInfoId", gi.getId());
//				    startActivity(intent);
					break;
				case 200://群邀请
//					intent = new Intent(ContactFrameActivity.this, MultichatroomSubscription.class);
//					intent.putExtra("inviter", gi.getMinviter());
//					intent.putExtra("jid", gi.getMfrom());
//					intent.putExtra("roomname", gi.getMroomname());
//					intent.putExtra("greetInfoId", gi.getId());
//					startActivity(intent);
					break;
				case 300://系统消息
					intent = new Intent(ContactFrameActivity.this,NotificationDetailsActivity.class);
		            intent.putExtra(Constants.NOTIFICATION_ID, gi.getMadminmsgid());
		            intent.putExtra(Constants.NOTIFICATION_API_KEY, gi.getMadminmsgapikey());
		            intent.putExtra(Constants.NOTIFICATION_TITLE, gi.getMadminmsgtitle());
		            intent.putExtra(Constants.NOTIFICATION_MESSAGE, gi.getMadminmsgbody());
		            intent.putExtra(Constants.NOTIFICATION_URI, gi.getMadminmsguri());
		            intent.putExtra("greetInfoId", gi.getId());
//		            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		            intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//		            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);//baoliu
		            startActivity(intent);
					break;
				case 400://普通陌生人message消息
//					intent = new Intent(ContactFrameActivity.this,ChatPullRefListActivity.class);
//					intent.setData(Contact.makeXmppUri(gi.getMfrom()));
//					intent.putExtra("greetInfoId", gi.getId());
//					startActivity(intent);
//					gi.getMbody();
//					Toast.makeText(mContext, "普通消息400AAA="+gi.toString(), Toast.LENGTH_SHORT).show(); 
					intent = new Intent(ContactFrameActivity.this,ChatPullRefListActivity.class);
					intent.putExtra("jid", gi.getMfrom());
					startActivity(intent);
					break;
				default:
					break;
			}
		}
    }
    /**
     * 常按某推送消息，打开弹出菜单，删除*/
    private SimpleListDialog mDialog = null;
    String[] codes = new String[] { "删除招呼消息" };
    
    public class GreetListOnLongClick implements OnItemLongClickListener{//OnItemLongClickListener
    	public GreetListOnLongClick(){
    		
    	}
    	@Override
    	public boolean onItemLongClick(AdapterView<?> arg0, View v, int pos, long lpos){
    		Log.e("※※※※※20141230长按GreetListOnLongClick※※※※※", "※※20141230长按GreetListOnLongClick");
    		mDialog = new SimpleListDialog(mContext);
			mDialog.setTitle("提示");
			mDialog.setTitleLineVisibility(View.GONE);
			mDialog.setAdapter(new SimpleListDialogAdapter(mContext, codes));
			mDialog.setOnSimpleListItemClickListener(new OnReplyDialogItemClickListener(pos-1
					));
			mDialog.show();
    		return true;
    	}
    }
	
    private class OnReplyDialogItemClickListener implements
	onSimpleListItemClickListener {
    	int mItemid = 0;
    	GreetInfo gi = null;
    	public OnReplyDialogItemClickListener(int itemid) {
    		mItemid = itemid;
    	}
    	@Override
		public void onItemClick(int position) {
    		switch (position) {
	    		case 0:
	    			try{
		    			gi = list_greetinfos.get(mItemid);
		    			if(gi!=null){
		    				greetInfoAdapter.deleteGreetInfo(gi.getId());
		        			currentPage = 0;
		        			mType = 2;
		        			flag = true;
		        			getContactList(ConstantValues.refresh);
		    			}
	    			}catch(Exception e){
	    				e.printStackTrace();
	    			}
	    			break;
    		}
    	}
    }
    /**
     * Event simple click on item of the contact list.
     * 单击某联系人，打开chat聊天对话框
     */
//    private class BeemContactListOnClick implements PLA_ListView.OnItemClickListener {
    public class ContactGroupListOnClick implements OnItemClickListener {//private
		/**
		 * Constructor.
		 */
		public ContactGroupListOnClick( ) {
		}
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int pos, long lpos) {
////			ptrlv.getAdapter().getView(pos, v, ptrlv);  
//			ptrlv.getRefreshableView().getAdapter().getView(pos, v, ptrlv); 
//			RelativeLayout user_item_relative = (RelativeLayout)v.findViewById(R.id.user_item_relative);
//			BadgeView badgeView = new BadgeView(mContext, user_item_relative);
//            badgeView.setText("2");
//            badgeView.show();
////            holder.badgeView.hide();
            
			ViewHolder holder = (ViewHolder) v.getTag();
			if(holder.badgeView.isShown())
				holder.badgeView.hide();
//			holder.unreadmsgnumber.setVisibility(View.GONE);
			
			
		    ContactGroup c = (ContactGroup)linkedList.get(pos-1);//pos-1
		    
		    Toast.makeText(ContactFrameActivity.this, "单击：" + (pos-1), Toast.LENGTH_SHORT).show();
		    
		    UnReadMsgNumber unReadMsgNumber = new UnReadMsgNumber();
		    unReadMsgNumber.setKey(StringUtils.parseBareAddress(c.getJID()));
		    unReadMsgNumber.setUnreadnumber(0);
		    duitangInfoAdapter.addUnReadMsgNumber(unReadMsgNumber);
		    UnReadMsgNumberMap.put(StringUtils.parseBareAddress(c.getJID()), ""+0);
//		    
//		    
		    Intent i = new Intent(ContactFrameActivity.this,ChatPullRefListActivity.class);
//		    i.setData(c.getUuid());
//            if(c.getAvatarId()!=null 
//            		&& c.getAvatarId().length()!=0 
//            		&& !c.getAvatarId().equalsIgnoreCase("null")
//            		&& (
//            				c.getAvatarId().toLowerCase().endsWith(".jpg")
//            				|| c.getAvatarId().toLowerCase().endsWith(".png")
//            				|| c.getAvatarId().toLowerCase().endsWith(".bmp")
//            				|| c.getAvatarId().toLowerCase().endsWith(".gif")
//            			)
//            		&& c.getJIDWithRes().indexOf("@conference.")==-1)
//            	i.putExtra("headimg", XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(c.getJIDWithRes())+"/"+c.getAvatarId());//+"thumbnail_"
//		    i.putExtra("myheadimg", myheadimg);
//		    i.putExtra("username",c.getName());
//		    i.putExtra("myusername",myusername);
		    int type = c.getType();//0 contact,1 group
		    i.putExtra("type", type);
		    i.putExtra("uid", c.getUid());
		    i.putExtra("uuid", c.getUuid());
		    i.putExtra("username", c.getUsername());
		    i.putExtra("name", c.getName());
		    i.putExtra("avatarpath", c.getAvatarPath());
		    
		    i.putExtra("tagid", c.getTagid());
		    i.putExtra("tagname", c.getTagname());
		    i.putExtra("pic", c.getPic());//群组头像pic
		    i.putExtra("jid", c.getJID());
            startActivity(i);
		}
    }
    
    
    public int containsKey(String key){
    	int i = 0;
    		Iterator<ContactGroup> it = linkedList.iterator();
    		ContactGroup di;
    		while(it.hasNext()){
    			di = it.next();
    			
    		    if(StringUtils.parseBareAddress(di.getJID()).equals(key))
//    			if(di.getJID().equals(key))
    		    	return i;
    		    i++;
    		}
    	return -1;
    }
    /**
     * Listener on service event.
     */
    private class BeemRosterListener extends IBeemRosterListener.Stub {
		/**
		 * Constructor.
		 */
		public BeemRosterListener() {
		}
		/**
		 * {@inheritDoc}
		 * Simple stategy to handle the onEntriesAdded event.
		 * if contact has to be shown :
		 * <ul>
		 * <li> add him to his groups</li>
		 * <li> add him to the specials groups</>
		 * </ul>
		 */
		//List<String>
		@Override
		public void onEntriesAdded(final List addresses)  throws RemoteException{//throws RemoteException
			Log.d("ContactFrameActivity", "onEntries added " + addresses);
			ContactGroup cGroup = null;
//			LinkedList linkedList2 = new LinkedList();
			List<ContactGroup> datas = new ArrayList<ContactGroup>();
			if(mRoster!=null){
				Log.d("ContactFrameActivity", "onEntries added (mRoster!=null) = " + (mRoster!=null));
			    for (Object jid : addresses) {//1@0/admin   uid@type/username
			    	Log.d("ContactFrameActivity", "onEntries added jid = " + jid);
			    	String tmp = StringUtils.parseBareAddress((String)jid);
			    	String uid = StringUtils.parseBareAddress2(tmp);
			    	Log.d("ContactFrameActivity", "onEntries added tmp = " + tmp);
			    	Log.d("ContactFrameActivity", "onEntries added uid = " + uid);
			    	int type = 0;
			    	try{
			    		type = Integer.parseInt(StringUtils.parseResource2(tmp));
			    	}catch(Exception e){
			    		type = 0;
			    	}
			    	Log.d("ContactFrameActivity", "onEntries added type = " + type);
			    	cGroup = mRoster.getContact((String)jid,type);//此处有问题uid改成jid
			    	Log.d("ContactFrameActivity", "onEntries added cGroup = " + cGroup.toXML());
			    	//20141114 added by allen 好友添加or拒绝 需要更新 本地客户端好友列表缓存 start	
			    	savePersonInfoToDB(cGroup);//更新本地数据库记录20141014
			    	
//			    	datas.add(cGroup);
//			    	linkedList.add(cGroup);
			    	Log.d("ContactFrameActivity", "onEntries added cGroup.getJID() = " + cGroup.getJID());
			    	Message refresh_roster = null;
			    	int idx = containsKey(cGroup.getJID());
			    	Log.d("ContactFrameActivity", "onEntries added idx = " + idx);
            		if(idx!=-1){
//            			mList.remove(info);
            			linkedList.remove(idx);
            			linkedList.add(cGroup);
            			datas.add(cGroup);
            			refresh_roster = mHandler.obtainMessage(UPDATE_ROSTER_FINISH,
    							datas);
            		}else{
            			datas.add(cGroup);
    			    	linkedList.add(cGroup);
    			    	refresh_roster = mHandler.obtainMessage(REFRESH_ROSTER_FINISH,
    							datas);
            		}
            		
            		
//					refresh_roster = mHandler.obtainMessage(REFRESH_ROSTER_FINISH,
//							datas);
					mHandler.sendMessage(refresh_roster);
			    }
			}
		}
		/**
		 * {@inheritDoc}
		 * Simple stategy to handle the onEntriesDeleted event.
		 * <ul>
		 * <li> Remove the contact from all groups</li>
		 * </ul>
		 */
		@Override
		public void onEntriesDeleted(final List addresses)  throws RemoteException{
			Log.d("ContactFrameActivity", "onEntries deleted " + addresses);
			ContactGroup cGroup = null;
//			LinkedList linkedList2 = new LinkedList();
			List<ContactGroup> datas = new ArrayList<ContactGroup>();
			if(mRoster!=null){
				Log.d("ContactFrameActivity", "onEntries deleted (mRoster!=null) = " + (mRoster!=null));
			    for (Object jid : addresses) {//1@0/admin   uid@type/username
			    	Log.d("ContactFrameActivity", "onEntries deleted jid = " + jid);
			    	String tmp = StringUtils.parseBareAddress((String)jid);
			    	String uid = StringUtils.parseBareAddress2(tmp);
			    	Log.d("ContactFrameActivity", "onEntries deleted tmp = " + tmp);
			    	Log.d("ContactFrameActivity", "onEntries deleted uid = " + uid);
			    	int type = 0;
			    	try{
			    		type = Integer.parseInt(StringUtils.parseResource2(tmp));
			    	}catch(Exception e){
			    		type = 0;
			    	}
			    	Log.d("ContactFrameActivity", "onEntries deleted type = " + type);
			    	Log.d("ContactFrameActivity", "onEntries deleted cGroup000");
			    	//注意在核心包中Roster.java中RosterPacketListener中已经执行了onEntriesAdded,onEntriesDeleted,onEntriesUpdated方法更新了mRoster对象
//			    	Log.d("ContactFrameActivity", "onEntries deleted cGroup111 = " + mRoster.getContact((String)uid,type));//null 
////			    	Log.d("ContactFrameActivity", "onEntries deleted cGroup222 = " + mRoster.getContact((String)uid,type).toXML());
//			    	cGroup = mRoster.getContact((String)jid,type);//此处有问题uid改成jid
//			    	Log.d("ContactFrameActivity", "onEntries deleted cGroup333 = " + cGroup);
//			    	Log.d("ContactFrameActivity", "onEntries deleted cGroup444 = " + cGroup.toXML());
//			    	//20141114 added by allen 好友添加or拒绝 需要更新 本地客户端好友列表缓存 start	
////			    	savePersonInfoToDB(cGroup);//更新本地数据库记录20141014
//			    	datas.add(cGroup);
//			    	
//			    	int idx = containsKey(cGroup.getJID());
//            		if(idx!=-1)
//            			linkedList.remove(idx);
			    	
            		int idx = containsKey((String)jid);
            	    if(idx!=-1){
	            		cGroup = (ContactGroup)linkedList.get(idx);
	            		datas.add(cGroup);
	            		linkedList.remove(idx);
            	    }
//			    	mAdapter.addItemLast(datas);
//					mAdapter.notifyDataSetChanged();
//					ptrlv.onRefreshComplete();
					Message refresh_roster = mHandler.obtainMessage(DELETE_ROSTER_FINISH,
							datas);
					mHandler.sendMessage(refresh_roster);
			    }
			}			
		}
		/**
		 * {@inheritDoc}
		 * Simple stategy to handle the onEntriesUpdated event.
		 * 该方法暂时无用
		 * <ul>
		 * <li> Remove the contact from all groups</li>
		 * <li> if contact has to be shown add it to his groups</li>
		 * <li> if contact has to be shown add it to the specials groups</li>
		 * </ul>
		 */
		@Override
		public void onEntriesUpdated(final List addresses)  throws RemoteException{
			Log.d("ContactFrameActivity", "onEntries updated " + addresses);
			ContactGroup cGroup = null;
//			LinkedList linkedList2 = new LinkedList();
			List<ContactGroup> datas = new ArrayList<ContactGroup>();
			if(mRoster!=null){
				Log.d("ContactFrameActivity", "onEntries updated (mRoster!=null) = " + (mRoster!=null));
			    for (Object jid : addresses) {//1@0/admin   uid@type/username
			    	Log.d("ContactFrameActivity", "onEntries updated jid = " + jid);
			    	String tmp = StringUtils.parseBareAddress((String)jid);
			    	String uid = StringUtils.parseBareAddress2(tmp);
			    	Log.d("ContactFrameActivity", "onEntries updated tmp = " + tmp);
			    	Log.d("ContactFrameActivity", "onEntries updated uid = " + uid);
			    	int type = 0;
			    	try{
			    		type = Integer.parseInt(StringUtils.parseResource2(tmp));
			    	}catch(Exception e){
			    		type = 0;
			    	}
			    	Log.d("ContactFrameActivity", "onEntries updated type = " + type);
			    	cGroup = mRoster.getContact((String)jid,type);//此处有问题uid改成jid
			    	Log.d("ContactFrameActivity", "onEntries updated cGroup = " + cGroup.toXML());
			    	//20141114 added by allen 好友添加or拒绝 需要更新 本地客户端好友列表缓存 start	
			    	savePersonInfoToDB(cGroup);//更新本地数据库记录20141014
			    	datas.add(cGroup);
			    	
			    	int idx = containsKey(cGroup.getJID());
            		if(idx!=-1){
//            			mList.remove(info);
            			linkedList.remove(idx);
            			linkedList.add(cGroup);
            		}
//			    	mAdapter.addItemLast(datas);
//					mAdapter.notifyDataSetChanged();
//					ptrlv.onRefreshComplete();
					Message refresh_roster = mHandler.obtainMessage(UPDATE_ROSTER_FINISH,
							datas);
					mHandler.sendMessage(refresh_roster);
			    }
			}
		}
    }
    
    private class ChatManagerListener extends IChatManagerListener.Stub {

		/**
		 * Constructor.
		 */
		public ChatManagerListener() {
		}
	
		@Override
		public void chatCreated(IChat chat, boolean locally) {
		    if (locally)
			return;
		    try {
			    chat.addMessageListener(mMessageListener);
//			    mChatManager.deleteChatNotification(mChat);
		    } catch (RemoteException ex) {
			Log.e("MainListActivity", "A remote exception occurs during the creation of a chat", ex);
		    }
		}
    } 
    
	private final IMessageListener mMessageListener = new OnMessageListener();
    private class OnMessageListener extends IMessageListener.Stub {
    	
		/**
		 * Constructor.
		 */
		public OnMessageListener() {
		}
	
		/**
		 * {@inheritDoc}.
		 * handle the received messages and refresh the chat message list UI
		 */
		@Override
		public void processMessage(IChat chat, final com.stb.core.chat.Message msg) throws RemoteException {
		    final String fromBareJid = StringUtils.parseBareAddress(msg.getMfrom());
		    Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※ChatListener processMessage※※:from="+msg.getMfrom()+";body="+msg.getMbody());
		    //此处更新listview局部UI
		    int index = mAdapter.containsKey(StringUtils.parseBareAddress(msg.getMfrom()));
		    Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※index="+index);
		    if(index!=-1){//&& !chat.isOpen()
		    	
		    	updateUi4ptrlv((index+1),StringUtils.parseBareAddress(msg.getMfrom()),false);
		    }
		}
	
		/**
		 * {@inheritDoc}.
		 */
		@Override
		public void stateChanged(IChat chat) throws RemoteException {
	
		}
	
		@Override
		public void otrStateChanged(final String otrState) throws RemoteException {
	
		}
    }
    
    
	private void updateUi4ptrlv(final int index,final String username,final boolean isfromchatpull) {
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {
			
			private UnReadMsgNumber unReadMsgNumber = null;

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				if(isfromchatpull){
					unReadMsgNumber = new UnReadMsgNumber();
				    unReadMsgNumber.setKey(username);
				    unReadMsgNumber.setUnreadnumber(0);
				    duitangInfoAdapter.addUnReadMsgNumber(unReadMsgNumber);
				    UnReadMsgNumberMap.put(username, "0");
				    return true;
				}else{
					unReadMsgNumber = duitangInfoAdapter.getUnReadMsgNumber(username);
					if(unReadMsgNumber!=null){
						UnReadMsgNumberMap.put(username, ""+unReadMsgNumber.getUnreadnumber());
						return true;
					}else
						return false;
				}
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				if (!result) {
					mHandler3.sendEmptyMessage(11);
				} else {
//					mHandler2.sendEmptyMessage(12);
//					android.os.Message message = mHandler2.obtainMessage(12,index,unReadMsgNumber.getUnreadnumber());
					android.os.Message message = mHandler3.obtainMessage();
					message.arg1 = index;//index
					message.arg2 = unReadMsgNumber.getUnreadnumber();//number
					message.obj = username;//number
					message.what = 12;
		//								message.sendToTarget();
					mHandler3.sendMessage(message);
				}
			}

		});
	}
	//更新消息图章end
	
	private boolean isFirst = true;
	private boolean flagType = true;//true: contactlist false:greetInfos
    private ContactListsFragment contactListsFragment = null;
    private GreetInfosFragment greetInfosFragment = null;
	@Override
	public void onPtrlvSet(PullToRefreshListView mPtrlv){
		Log.e("MMMMMMMMMMMMContactFrameActivity(onPtrlvSet)MMMMMMMMMMMM", "++++++++++++++ContactFrameActivity(onPtrlvSet)");
		ptrlv = mPtrlv;
		flagType = true;
		mAdapter.notifyDataSetInvalidated();
		if(isFirst)
		getContactList(0);
		isFirst = true;
	}
	/**
	 * 解决android ListView 刷新数据,加载时遇到的数组越界问题：
	 * 1.不使用下拉刷新的headView?
	 * 2.当adapter的数据被全部clean时,使用adapter.notifyDataSetInvalidated(); 
	 * 3.在加入新的数据后,使用adapter.notifyDataSetChanged(); 
      */
	@Override
	public void onPtrlvSet2(PullToRefreshListView mPtrlv){
		ptrlv = mPtrlv;
		flagType = false;
		Log.e("MMMMMMMMMMMMContactFrameActivity(onPtrlvSet2)MMMMMMMMMMMM", "++++++++++++++ContactFrameActivity(onPtrlvSet2)");
		mAdapter.notifyDataSetInvalidated();
		if(isFirst)
		getContactList(0);
		isFirst = true;
//		mAdapter.notifyDataSetChanged();
	}
	
	
	//处理 greetinfos 20141102 start
	public void initGreetInfos_first(){
		try{
			//记录总数
			greetTotalCount = (int)greetInfoAdapter.getAllGreetInfosCount();
			Log.e("MMMMMMMMMMMM20141102flagType initGreetInfos_firstMMMMMMMMMMMM", "++++++++++++++greetTotalCount="+greetTotalCount);
			//总页码
			greetPageCount = greetTotalCount%greetPageSize==0? greetTotalCount/greetPageSize-1 : greetTotalCount/greetPageSize;
			
			Log.e("MMMMMMMMMMMM20141102flagType initGreetInfos_firstMMMMMMMMMMMM", "++++++++++++++greetPageCount="+greetPageCount);
			list_greetinfos = greetInfoAdapter.getGreetInfosByPageIndex(StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID()),greetPageSize, 0);
			Log.e("MMMMMMMMMMMM20141102flagType initGreetInfos_firstMMMMMMMMMMMM", "++++++++++++++(list_greetinfos!=null)="+(list_greetinfos!=null));
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public boolean initGreetInfos(){
		try{
			//记录总数
			greetTotalCount = (int)greetInfoAdapter.getAllGreetInfosCount();
			//总页码
			greetPageCount = greetTotalCount%greetPageSize==0? greetTotalCount/greetPageSize-1 : greetTotalCount/greetPageSize;
			list_greetinfos = greetInfoAdapter.getGreetInfosByPageIndex(StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID()),greetPageSize, greetCurrentPage);
			return true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	//处理 greetinfos 20141102 end
	
	private int mType = 0;//1 pulldown 2 pullup
	
	
	public void savePersonInfoToDB(ContactGroup contact){
		if(contact!=null){
	    	DuitangInfo newsInfo1 = new DuitangInfo();
	    	
	    	int cgrouptype = contact.getType();////0 contact,1 group
			switch(cgrouptype){
				case 0:
			        newsInfo1.setKey(contact.getJID());
			        newsInfo1.setAlbid(contact.getUsername());//username
			       
			        newsInfo1.setIsrc(contact.getAvatarPath());//contact.getAvatarId()  
			        newsInfo1.setMsg(contact.getName()+"\n"+StringUtils.parseName(contact.getJID()));
			        newsInfo1.setName(contact.getName());
			        
			        newsInfo1.setHeight(60);
			        newsInfo1.setWidth(60);	
			       
			        newsInfo1.setGender(contact.getSex()+"");//0 默认未知，1男，2女
		
			        int age = 0;
		            if(contact.getBirthyear()!=null
		            		&& !contact.getBirthyear().equalsIgnoreCase("null")
		            		&& contact.getBirthyear().length()!=0
		            		&& contact.getBirthmonth()!=null
		            		&& !contact.getBirthmonth().equalsIgnoreCase("null")
		            		&& contact.getBirthmonth().length()!=0
		            		&& contact.getBirthday()!=null
		            		&& !contact.getBirthday().equalsIgnoreCase("null")
		            		&& contact.getBirthday().length()!=0){
		            	
		            	try{
		            		age = TextUtils.getAge(Integer.parseInt(contact.getBirthyear()),
		            				Integer.parseInt(contact.getBirthmonth()),
		            				Integer.parseInt(contact.getBirthday()));
		            	}catch(Exception e){
		            		e.printStackTrace();
		            		age = 0;
		            	}
		            }
		            if(age>200)
		            	newsInfo1.setBirthday("未知");
		            else
		            	newsInfo1.setBirthday(age+"");
		            
			        newsInfo1.setSign(contact.getNote());
			        break;
			        
				case 1:
					
			        newsInfo1.setKey(contact.getJID());
			        newsInfo1.setAlbid(contact.getTagname());//tagname
			       
			        newsInfo1.setIsrc(contact.getPic());//contact.getPic().replace("localhost", "10.0.2.2")
			        newsInfo1.setMsg(contact.getTagname()+"\n"+StringUtils.parseName(contact.getJID()));
			        newsInfo1.setName(contact.getTagname());
			        
			        newsInfo1.setHeight(60);
			        newsInfo1.setWidth(60);	
			       
			        newsInfo1.setGender(contact.getSex()+"");//0 默认未知，1男，2女
		
			        
		            newsInfo1.setBirthday("群组");
		            
			        newsInfo1.setSign(contact.getSubject());
					break;
			}
	        duitangInfoAdapter.addDuitangInfo(newsInfo1);//用户信息存入本地数据库
		}
	}
	
	
	
	public String sprintf(String format, double number) {
		return new DecimalFormat(format).format(number);
	}
	//sizeType :big,middle,small
	//type : real 或 ""
	public String avatar_file(int uid, String sizeType, String type) {
		String var = "avatarfile_" + uid + "_" + sizeType + "_" + type;
		String avatarPath = "";
			uid = Math.abs(uid);
			String struid = sprintf("000000000", uid);
			String dir1 = struid.substring(0, 3);
			String dir2 = struid.substring(3, 5);
			String dir3 = struid.substring(5, 7);
			StringBuffer avater = new StringBuffer();
			avater.append(dir1 + "/" + dir2 + "/" + dir3 + "/" + struid.substring(struid.length() - 2));
			avater.append("real".equals(type) ? "_real_avatar_" : "_avatar_");
			avater.append(sizeType + ".jpg");
			avatarPath = avater.toString();

		return avatarPath;
	}
}
